package com.example.myedittext;

import static android.os.Build.VERSION_CODES.R;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity2 extends AppCompatActivity {
    // Socket变量
    private Socket socket;

    // 线程池
    // 为了方便展示,此处直接采用线程池进行线程管理,而没有一个个开线程
    private ExecutorService mThreadPool;
    private static final String TAG = "MainActivity2";
    // 接收服务器发送过来的消息

    String response;

    // 连接 发送数据到服务器 的按钮变量
    private Button btnSend;

    // 显示接收服务器消息
    private TextView receive_message;

    // 输入需要发送的消息 输入框
    private EditText mEdit;
    public int i = 0;

//    @Async
    private void connectToServer(String ip, int port) {
        mThreadPool.execute(() -> {
            try {
                socket = new Socket(ip, port);
                //接收数据
                try {
                    InputStreamReader Socin = new InputStreamReader(socket.getInputStream());  //从socket 读取
                    BufferedReader SocBuf = new BufferedReader(Socin);
                    response = SocBuf.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                //接收到的显示在屏幕上
                receive_message.append(response +"\n");
                // 启动接收消息的线程
//                mThreadPool.execute(this::receiveMessages);
            } catch (IOException e) {
                Log.e(TAG, "连接服务器失败", e);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        //拿到从第一个页面传来的数据
        Intent intent = getIntent();
        // 初始化所有按钮
        btnSend = (Button) findViewById(R.id.btn_send);
        mEdit = (EditText) findViewById(R.id.et_inf);
        receive_message = (TextView) findViewById(R.id.text_view);
        System.out.println("按钮初始化完成");

        String ip = intent.getStringExtra("IP");
        int port = Integer.parseInt(Objects.requireNonNull(intent.getStringExtra("PORT")));

        // 初始化线程池
        mThreadPool = Executors.newCachedThreadPool();

        // 连接服务器
        connectToServer(ip, port);
//        if(i==0){
//            //创建客户端
//            String ip = intent.getStringExtra("IP");
//            int port = Integer.parseInt(Objects.requireNonNull(intent.getStringExtra("PORT")));
//            try {
//                socket = new Socket(ip, port);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//            i=1;
//        }
//
//        //接收数据
//        try {
//            InputStreamReader Socin = new InputStreamReader(socket.getInputStream());  //从socket 读取
//            BufferedReader SocBuf = new BufferedReader(Socin);
//            response = SocBuf.readLine();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        //接收到的显示在屏幕上
//        receive_message.append(response +"\n");

        /*
         * 发送消息 给 服务器
         */
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("点击了发送");
//                Log.v(TAG,"点击了发送");
                // 利用线程池直接开启一个线程 & 执行该线程
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try{
//                            if(i==0){
//                                //创建客户端192.168.31.71
////                                socket = new Socket("192.168.3.32", 8082);//7890
//                                String ip = intent.getStringExtra("IP");
//                                int port = Integer.parseInt(Objects.requireNonNull(intent.getStringExtra("PORT")));
//                                socket = new Socket(ip, port);//7890
//                                i=1;
//                            }
                            //建立连接
                            InputStreamReader Sysin = new InputStreamReader(System.in);  //键盘输入

                            InputStreamReader Socin = new InputStreamReader(socket.getInputStream());  //从socket 读取
                            BufferedReader SocBuf = new BufferedReader(Socin);

                            PrintWriter Socout = new PrintWriter(socket.getOutputStream());   //数据写入socket
                            //进行通信
                            //读取键盘键入的字符
                            String readline = mEdit.getText().toString();
                            System.out.println("发送:"+readline);
                            Log.v(TAG,"发送:"+readline);
                            //发送给服务器，再接收，是一个循环
                            if(!readline.equals("ok"))    //发送的数据不能为bye
                            {
                                Socout.println(readline);//写入socket
                                Socout.flush();
                                //发送的消息显示在屏幕上
//                              receive_message.append(mEdit.getText().toString()+"\n");

                                //接收数据
                                response = SocBuf.readLine();
                                System.out.println("接收到:"+response);//打印接受到的
                                Log.v(TAG,"接收到:"+response);
                                //接收到的显示在屏幕上
                                receive_message.append(response +"\n");
                            }
                            else {
                                receive_message.append("下线了bye" +"\n");
                                Socout.close();
                                Socin.close();
                                socket.close();
                            }
                        }catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                 //接收消息
                  mThreadPool.execute(new Runnable() {
                          @Override
                          public void run() {
                              try (ServerSocket serverSocket = new ServerSocket(8083)) {
                                  System.out.println("等待连接...");
                                  try (Socket socket = serverSocket.accept()) {
                                      System.out.println("建立连接");
                                      try (InputStreamReader socIn = new InputStreamReader(socket.getInputStream());
                                           BufferedReader socBuf = new BufferedReader(socIn);
                                           PrintWriter socOut = new PrintWriter(socket.getOutputStream(), true);
                                           InputStreamReader sysIn = new InputStreamReader(System.in);
                                           BufferedReader sysBuf = new BufferedReader(sysIn)) {

                                          System.out.println("建立输出流");
                                          System.out.println("socket连接成功");

                                          while (true) {
                                              try {
                                                  String message = socBuf.readLine();
                                                  if(message == null || message.equals("") || message.equals("null")){
                                                      System.out.println("客户端关闭了连接");
                                                      break;
                                                  }
                                                  System.out.println("收到消息: " + message);

                                                  //接收数据
                                                  response = sysBuf.readLine();
                                                  //接收到的显示在屏幕上
                                                  receive_message.append(response +"\n");
                                                  // 处理消息并发送响应
                                                  socOut.println("已收到消息: " + message);
                                              } catch (SocketException e) {
                                                  System.err.println("连接重置: " + e.getMessage());
                                                  break;
                                              } catch (IOException e) {
                                                  System.err.println("IO异常: " + e.getMessage());
                                                  break;
                                              }
                                          }
                                      }
                                  } catch (Exception e) {
                                      System.err.println("Error: " + e.getMessage());
                                      e.printStackTrace();
                                  }
                              } catch (Exception e) {
                                  System.err.println("Error: " + e.getMessage());
                                  e.printStackTrace();
                              }

                          }
                  }
                );

            }
        });

    }
}

